<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from '../utils/axios';
import { localGet } from '../utils';

// 路由和状态管理
const route = useRoute();
const router = useRouter();

// 表单数据
const formData = ref({
  title: '',
  description: '',
  tags: [] as string[],
  type: 1, // 1:出售, 2:出租
  categoryId: null as number | null,
  images: [] as string[],
  price: null as number | null,
  rentType: null as number | null, // 1:按天,2:按周,3:按月
  rentCount: null as number | null,
  currentTag: '' // 当前输入的标签
});

// 分类选项
const categories = ref([]);
const loading = ref(false);
const toastMessage = ref('');
const showToast = ref(false);

// 从路由参数获取发布类型
const publishType = route.params.type || 'sell';

// 初始化表单类型
if (publishType === 'rent') {
  formData.value.type = 2;
}

// 显示提示消息
const showMessage = (message: string) => {
  toastMessage.value = message;
  showToast.value = true;
  setTimeout(() => {
    showToast.value = false;
  }, 2000);
};

// 获取物品分类
const fetchCategories = async () => {
  try {
    const response = await axios.get('/api/itemCategories/sel');
    if (response.code === 200) {
      categories.value = response.data;
    }
  } catch (error) {
    console.error('获取分类失败:', error);
    showMessage('获取分类失败');
  }
};

// 添加标签
const addTag = () => {
  if (formData.value.currentTag.trim() && !formData.value.tags.includes(formData.value.currentTag.trim())) {
    formData.value.tags.push(formData.value.currentTag.trim());
    formData.value.currentTag = '';
  }
};

// 移除标签
const removeTag = (index: number) => {
  formData.value.tags.splice(index, 1);
};

// 处理标签输入
const handleTagInput = (e: KeyboardEvent) => {
  if (e.key === 'Enter' || e.key === ',') {
    e.preventDefault();
    addTag();
  }
};

// 图片上传处理（简化版，实际项目中需要实现完整上传逻辑）
const handleImageUpload = (e: Event) => {
  const target = e.target as HTMLInputElement;
  if (target.files && target.files.length > 0) {
    // 这里简化处理，实际项目中需要上传到服务器并获取URL
    const file = target.files[0];
    const reader = new FileReader();
    reader.onload = (e) => {
      if (e.target && typeof e.target.result === 'string') {
        formData.value.images.push(e.target.result);
      }
    };
    reader.readAsDataURL(file);
  }
};

// 移除图片
const removeImage = (index: number) => {
  formData.value.images.splice(index, 1);
};

// 提交表单
const submitForm = async () => {
  // 表单验证
  if (!formData.value.title.trim()) {
    showMessage('请输入物品标题');
    return;
  }

  if (!formData.value.description.trim()) {
    showMessage('请输入物品描述');
    return;
  }

  if (!formData.value.categoryId) {
    showMessage('请选择物品分类');
    return;
  }

  if (!formData.value.price || formData.value.price <= 0) {
    showMessage('请输入正确的价格');
    return;
  }

  // 如果是出租，验证出租类型和数量
  if (formData.value.type === 2) {
    if (!formData.value.rentType) {
      showMessage('请选择出租方式');
      return;
    }

    if (!formData.value.rentCount || formData.value.rentCount <= 0) {
      showMessage('请输入正确的出租数量');
      return;
    }
  }

  loading.value = true;

  try {
    // 准备提交数据 - 修复标签格式问题
    const submitData = {
      title: formData.value.title,
      description: formData.value.description,
      tag: JSON.stringify(formData.value.tags), // 将标签数组转换为JSON字符串格式：["标签1","标签2"]
      type: formData.value.type,
      categoryId: formData.value.categoryId,
      images: JSON.stringify(formData.value.images), // 图片数组也转为JSON字符串
      price: formData.value.price,
      rentType: formData.value.rentType,
      rentCount: formData.value.rentCount
    };

    console.log("提交数据:");
    console.log(submitData);

    // 获取当前用户ID（实际项目中应从登录状态获取）
    const userId = localGet('userId') || 1;
    submitData.userId = userId;

    const response = await axios.post('/api/userItems/add', submitData);

    if (response.code === 200) {
      showMessage('发布成功');
      setTimeout(() => {
        router.push('/home'); // 发布成功后跳转到首页
      }, 1500);
    } else {
      showMessage(response.msg || '发布失败');
    }
  } catch (error) {
    console.error('发布失败:', error);
    showMessage('发布失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 返回上一页
const goBack = () => {
  router.go(-1);
};

// 组件挂载时获取分类数据
onMounted(() => {
  fetchCategories();
});
</script>

<template>
  <div class="publish-page">
    <!-- 顶部导航栏 -->
    <div class="app-header">
      <div class="back-btn" @click="goBack">
        <i class="fas fa-arrow-left"></i>
      </div>
      <div class="app-title">{{ publishType === 'rent' ? '发布出租' : '发布出售' }}</div>
      <div class="header-placeholder"></div>
    </div>

    <!-- 表单内容 -->
    <div class="container">
      <div class="form-section">
        <!-- 物品标题 -->
        <div class="form-group">
          <label class="form-label">物品标题 *</label>
          <input
              v-model="formData.title"
              type="text"
              class="form-input"
              placeholder="请输入物品标题"
              maxlength="50"
          >
          <div class="char-count">{{ formData.title.length }}/50</div>
        </div>

        <!-- 物品描述 -->
        <div class="form-group">
          <label class="form-label">物品描述 *</label>
          <textarea
              v-model="formData.description"
              class="form-textarea"
              placeholder="请详细描述物品的状况、特点等信息"
              rows="4"
              maxlength="500"
          ></textarea>
          <div class="char-count">{{ formData.description.length }}/500</div>
        </div>

        <!-- 标签输入 -->
        <div class="form-group">
          <label class="form-label">物品标签</label>
          <div class="tags-input-container">
            <input
                v-model="formData.currentTag"
                type="text"
                class="form-input tags-input"
                placeholder="输入标签后按回车或逗号添加"
                @keydown="handleTagInput"
            >
            <button class="add-tag-btn" @click="addTag">添加</button>
          </div>
          <div class="tags-container">
            <span
                v-for="(tag, index) in formData.tags"
                :key="index"
                class="tag"
            >
              #{{ tag }}
              <span class="remove-tag" @click="removeTag(index)">×</span>
            </span>
          </div>
          <div class="form-hint">标签可以帮助其他用户更容易找到您的物品</div>
        </div>

        <!-- 物品分类 -->
        <div class="form-group">
          <label class="form-label">物品分类 *</label>
          <select v-model="formData.categoryId" class="form-select">
            <option value="" disabled selected>请选择分类</option>
            <option v-for="category in categories" :key="category.categoryId" :value="category.categoryId">
              {{ category.name }}
            </option>
          </select>
        </div>

        <!-- 价格输入 -->
        <div class="form-group">
          <label class="form-label">{{ formData.type === 2 ? '出租单价' : '出售价格' }} *</label>
          <div class="price-input-container">
            <span class="currency-symbol">¥</span>
            <input
                v-model.number="formData.price"
                type="number"
                class="form-input price-input"
                placeholder="0.00"
                min="0"
                step="0.01"
            >
          </div>
        </div>

        <!-- 出租相关字段（仅当类型为出租时显示） -->
        <div v-if="formData.type === 2" class="form-group">
          <label class="form-label">出租方式 *</label>
          <div class="rent-options">
            <label class="rent-option">
              <input
                  v-model="formData.rentType"
                  type="radio"
                  name="rentType"
                  :value="1"
              >
              <span>按天</span>
            </label>
            <label class="rent-option">
              <input
                  v-model="formData.rentType"
                  type="radio"
                  name="rentType"
                  :value="2"
              >
              <span>按周</span>
            </label>
            <label class="rent-option">
              <input
                  v-model="formData.rentType"
                  type="radio"
                  name="rentType"
                  :value="3"
              >
              <span>按月</span>
            </label>
          </div>
        </div>

        <div v-if="formData.type === 2 && formData.rentType" class="form-group">
          <label class="form-label">出租{{
              formData.rentType === 1 ? '天数' :
                  formData.rentType === 2 ? '周数' : '月数'
            }} *</label>
          <input
              v-model.number="formData.rentCount"
              type="number"
              class="form-input"
              :placeholder="`请输入出租${formData.rentType === 1 ? '天数' : formData.rentType === 2 ? '周数' : '月数'}`"
              min="1"
          >
        </div>

        <!-- 图片上传 -->
        <div class="form-group">
          <label class="form-label">物品图片</label>
          <div class="image-upload-container">
            <div
                v-for="(image, index) in formData.images"
                :key="index"
                class="image-preview"
            >
              <img :src="image" :alt="`物品图片${index + 1}`">
              <div class="image-remove" @click="removeImage(index)">×</div>
            </div>
            <label class="image-upload-btn" v-if="formData.images.length < 5">
              <input
                  type="file"
                  accept="image/*"
                  @change="handleImageUpload"
                  style="display: none;"
              >
              <i class="fas fa-plus"></i>
              <span>添加图片</span>
            </label>
          </div>
          <div class="form-hint">最多可上传5张图片</div>
        </div>
      </div>

      <!-- 底部提交按钮 -->
      <div class="submit-section">
        <button
            class="submit-btn-bottom"
            @click="submitForm"
            :class="{ 'loading': loading }"
            :disabled="loading"
        >
          {{ loading ? '发布中...' : '发布物品' }}
        </button>
      </div>

      <div class="safe-area"></div>
    </div>

    <!-- Toast 提示 -->
    <div v-if="showToast" class="toast-message toast-visible">
      {{ toastMessage }}
    </div>
  </div>
</template>

<style scoped>
.publish-page {
  min-height: 100vh;
  background-color: #f8f9fa;
  color: #2c3e50;
  overflow-x: hidden;
  position: relative;
  font-family: 'Nunito', 'PingFang SC', -apple-system, BlinkMacSystemFont, sans-serif;
}

.publish-page * {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  -webkit-tap-highlight-color: transparent;
}

/* 顶部导航栏 */
.app-header {
  position: sticky;
  top: 0;
  height: 60px;
  background-color: #4267F4;
  display: flex;
  align-items: center;
  padding: 0 20px;
  z-index: 100;
}

.back-btn {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  color: white;
  cursor: pointer;
  transition: background-color 0.2s;
}

.back-btn:hover {
  background-color: rgba(255, 255, 255, 0.2);
}

.app-title {
  flex: 1;
  text-align: center;
  font-size: 18px;
  font-weight: 600;
  color: white;
}

.header-placeholder {
  width: 60px; /* 保持与back-btn对称 */
}

.container {
  width: 100%;
  max-width: 100%;
  padding: 20px 16px;
  margin: 0 auto;
  padding-bottom: 100px; /* 为底部按钮留出空间 */
}

.form-section {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  background-color: white;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.form-label {
  display: block;
  font-weight: 600;
  margin-bottom: 8px;
  color: #2c3e50;
}

.form-input, .form-textarea, .form-select {
  width: 100%;
  padding: 12px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  font-size: 16px;
  transition: border-color 0.2s;
}

.form-input:focus, .form-textarea:focus, .form-select:focus {
  outline: none;
  border-color: #4267F4;
}

.form-textarea {
  resize: vertical;
  min-height: 100px;
}

.char-count {
  text-align: right;
  font-size: 12px;
  color: #7f8c8d;
  margin-top: 4px;
}

.tags-input-container {
  display: flex;
  gap: 8px;
}

.tags-input {
  flex: 1;
}

.add-tag-btn {
  padding: 0 16px;
  background-color: #4267F4;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 600;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 8px;
}

.tag {
  display: inline-flex;
  align-items: center;
  background-color: #EDF2FD;
  color: #4267F4;
  padding: 4px 8px;
  border-radius: 16px;
  font-size: 14px;
}

.remove-tag {
  margin-left: 4px;
  cursor: pointer;
  font-weight: bold;
}

.price-input-container {
  position: relative;
  display: flex;
  align-items: center;
}

.currency-symbol {
  position: absolute;
  left: 12px;
  color: #7f8c8d;
  font-weight: 600;
}

.price-input {
  padding-left: 30px;
}

.rent-options {
  display: flex;
  gap: 16px;
}

.rent-option {
  display: flex;
  align-items: center;
  gap: 4px;
  cursor: pointer;
}

.image-upload-container {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.image-preview {
  position: relative;
  width: 80px;
  height: 80px;
  border-radius: 8px;
  overflow: hidden;
}

.image-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-remove {
  position: absolute;
  top: 4px;
  right: 4px;
  width: 20px;
  height: 20px;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  cursor: pointer;
}

.image-upload-btn {
  width: 80px;
  height: 80px;
  border: 2px dashed #e0e0e0;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #7f8c8d;
  cursor: pointer;
  transition: all 0.2s;
}

.image-upload-btn:hover {
  border-color: #4267F4;
  color: #4267F4;
}

.form-hint {
  font-size: 12px;
  color: #7f8c8d;
  margin-top: 4px;
}

/* 底部提交按钮区域 */
.submit-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 16px;
  background: linear-gradient(transparent, #f8f9fa 30%);
  z-index: 99;
}

.submit-btn-bottom {
  width: 100%;
  padding: 16px;
  background-color: #4267F4;
  color: white;
  border: none;
  border-radius: 12px;
  font-size: 18px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: 0 4px 12px rgba(66, 103, 244, 0.3);
}

.submit-btn-bottom:hover:not(:disabled) {
  background-color: #3555d5;
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(66, 103, 244, 0.4);
}

.submit-btn-bottom:active:not(:disabled) {
  transform: translateY(0);
}

.submit-btn-bottom.loading,
.submit-btn-bottom:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
}

/* 底部安全区域填充 */
.safe-area {
  height: env(safe-area-inset-bottom);
  padding-bottom: 80px; /* 为固定按钮留出空间 */
}

/* Toast 消息 */
.toast-message {
  position: fixed;
  bottom: 120px; /* 调整位置避免与底部按钮重叠 */
  left: 50%;
  transform: translateX(-50%) translateY(100px);
  padding: 12px 24px;
  background-color: #4267F4;
  color: white;
  border-radius: 6px;
  box-shadow: 0 4px 12px rgba(66, 103, 244, 0.3);
  z-index: 1000;
  font-weight: 500;
  transition: all 0.3s ease;
  opacity: 0;
  font-size: 14px;
}

.toast-visible {
  opacity: 1;
  transform: translateX(-50%) translateY(0);
}

/* 深色模式支持 */
@media (prefers-color-scheme: dark) {
  .publish-page {
    background-color: #1a1d21;
    color: #ecf0f1;
  }

  .form-group {
    background-color: #2c3e50;
  }

  .form-label {
    color: #ecf0f1;
  }

  .form-input, .form-textarea, .form-select {
    background-color: #34495e;
    border-color: #4a5f7a;
    color: #ecf0f1;
  }

  .tag {
    background-color: #34495e;
  }

  .image-upload-btn {
    border-color: #4a5f7a;
  }

  .submit-section {
    background: linear-gradient(transparent, #1a1d21 30%);
  }
}
</style>